package com.varma.android.aws.webserver;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;

import org.apache.commons.fileupload.MultipartStream;
import org.apache.commons.fileupload.MultipartStream.ProgressNotifier;
import org.apache.commons.io.FileUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.impl.DefaultHttpServerConnection;
import org.apache.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;

import com.varma.android.aws.R;
import com.varma.android.aws.app.AppLog;
import com.varma.android.aws.constants.Constants;
import com.varma.android.aws.ui.AWSMessageActivity;
import com.varma.android.aws.utility.Utility;

public class UploadCommandHandler implements HttpRequestHandler
{
    private static final long[] VIBRATE = { 0, 100, 200, 200, 100, 300 };

    private Context context = null;

    private boolean DEBUG = true;

    private String encoding = "ASCII";

    public UploadCommandHandler(Context context)
    {
        this.context = context;
        // this.serverConnection = notifyManager;

    }

    public void processRequest(HttpRequest request)
    {

        // DiskFileItemFactory factory = new DiskFileItemFactory();
        //
        // // Set factory constraints
        // factory.setSizeThreshold(100000);
        // factory.setRepository(context.getFilesDir());
        //
        // // Create a new file upload handler
        // ServletFileUpload upload = new ServletFileUpload(factory);
        //
        // // Set overall request size constraint
        // // upload.setSizeMax(yourMaxRequestSize);
        // // javax.servlet.http.HttpServletRequest
        // // Parse the request
        // HttpServletRequest re = null;// =new HttpServletRequest();
        //
        // try
        // {
        // List<FileItem> items = upload.parseRequest(re);
        // } catch (FileUploadException e)
        // {
        // // TODO Auto-generated catch block
        // e.printStackTrace();
        // }

    }

    @Override
    public void handle(HttpRequest request, HttpResponse response, HttpContext httpContext) throws HttpException,
        IOException
    {

        // parseRequest(request);

        String uriString = request.getRequestLine().getUri();
        Uri uri = Uri.parse(uriString);

        String method = request.getRequestLine().getMethod();

        ;

        Header[] headers = request.getAllHeaders();

        String boundry = "";
        for (int i = 0; i < headers.length; i++)
        {
            AppLog.logString("Message Header: " + headers[i].getName() + " :" + headers[i].getValue());

            String headerValue = headers[i].getValue();
            if (headerValue.contains("boundary="))
            {
                boundry = headerValue.substring(headerValue.indexOf("boundary=") + "boundary=".length());
            }

        }

        // DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
        // conn.bind(socket, new BasicHttpParams());
        // HttpRequest request = conn.receiveRequestHeader();

        // String method = request.getRequestLine().getMethod().toUpperCase();
        if (method.equals("POST"))
        {

            if (request instanceof HttpEntityEnclosingRequest)
            {
                HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
                InputStream input = entity.getContent();
                // MultipartEntity multi=new MultipartEntity();
                // MultipartEntity

                MultipartStream multipartStream =// new MultipartStream(input, boundry.getBytes());
                  new  MultipartStream(input,
                    boundry.getBytes(),
                    1024,
                    null);
                boolean nextPart = multipartStream.skipPreamble();

                File f = new File(context.getFilesDir() + "/a.apk");

                OutputStream output = new FileOutputStream(f, false);
                
// context.openFileOutput(
//     context.getFilesDir() + "/a.apk", Context.MODE_WORLD_READABLE);
          
                
                RandomAccessFile  raf = new RandomAccessFile(context.getFilesDir() + "/a.apk", "rw");
               
                while (nextPart)
                {
                    String header = multipartStream.readHeaders();
                    // process headers
                    // create some output stream
                    multipartStream.readBodyData(output);
                    
                    output.flush();
                    output.close();
                    AppLog.logString("multipartStream header:" + header);
                    nextPart = multipartStream.readBoundary();
                    break;
                }

                byte[] buf = new byte[1024];

                String filePath = context.getFilesDir() + "/a.apk";
                // RandomAccessFile raf = new RandomAccessFile(filePath, "rw");

                // byte[] entityContent = EntityUtils.toByteArray(entity);

                /**
                 * Incoming entity content -----------------------------11979242427070 01-01 13:11:40.136: I/aws(4683):
                 * Content-Disposition: form-data; name="file1"; filename="" 01-01 13:11:40.136: I/aws(4683):
                 * Content-Type: application/octet-stream 01-01 13:11:40.136: I/aws(4683): 01-01 13:11:40.136:
                 * I/aws(4683): 01-01 13:11:40.136: I/aws(4683): -----------------------------11979242427070 01-01
                 * 13:11:40.136: I/aws(4683): Content-Disposition: form-data; name="button" 01-01 13:11:40.136:
                 * I/aws(4683): 01-01 13:11:40.136: I/aws(4683): submit 01-01 13:11:40.136: I/aws(4683):
                 * -----------------------------11979242427070--
                 */
                AppLog.logString("boundry:" + boundry);

                int per = (android.os.FileUtils.S_IRWXU | android.os.FileUtils.S_IRWXG | android.os.FileUtils.S_IXOTH);
               // android.os.FileUtils.setPermissions(context.getFilesDir().getAbsolutePath(), per, -1, -1);
                AppLog.logString("AbsolutePath setPermissions:" + context.getFilesDir().getAbsolutePath());
                
                android.os.FileUtils.setPermissions(f.getAbsolutePath(), android.os.FileUtils.S_IRUSR | android.os.FileUtils.S_IWUSR | android.os.FileUtils.S_IRGRP | android.os.FileUtils.S_IROTH, -1, -1) ;
               
                Intent intent = new Intent(Intent.ACTION_VIEW);

                intent.setDataAndType(Uri.fromFile(f),

                    "application/vnd.android.package-archive");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                context.startActivity(intent);

                // AppLog.logString("Incoming entity content " + new String(entityContent));
                AppLog.logString("Incoming entity content (bytes): " + f.length());

            }

        }

        // String message = URLDecoder.decode(uri.getQueryParameter("msg"));

        AppLog.logString("Message URI: " + uriString);
        AppLog.logString("Message method: " + method + " length:");

        // displayMessage(message);

        HttpEntity entity = new EntityTemplate(new ContentProducer()
        {
            public void writeTo(final OutputStream outstream) throws IOException
            {
                OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
                String resp = Utility.openHTMLString(context, R.raw.messagesend);

                writer.write(resp);
                writer.flush();
            }
        });

        response.setHeader("Content-Type", "text/html");
        response.setEntity(entity);
    }

    private void parseRequest(HttpRequest request)
    {
        // DiskFileItemFactory factory = new DiskFileItemFactory();
        // ServletFileUpload upload = new ServletFileUpload(factory);
        // upload.setHeaderEncoding("UTF-8");
        //
        // // HttpServletRequest server=new HttpServletRequest();
        //
        // List fileItems = upload.parseRequest(server);
        // Iterator iter = fileItems.iterator();
        // while (iter.hasNext()) {
        // FileItem item = (FileItem) iter.next();
        // item.getInputStream();
        // if (!item.isFormField()) {
        // //文件流
        // }else{
        // //非文件流
        // String value=item.getString();
        // value = new String(value.getBytes("ISO-8859-1"),"UTF-8");
        //
        // }

        // }
    }

    private void handleUpload(DefaultHttpServerConnection connection, HttpRequest request) throws HttpException,
        IOException
    {
        HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 200, "OK");
        BasicHttpEntityEnclosingRequest enclosingRequest =
            new BasicHttpEntityEnclosingRequest(request.getRequestLine());
        if (request instanceof HttpEntityEnclosingRequest)
        {
            if (connection.isOpen())
            {
                connection.receiveRequestEntity((HttpEntityEnclosingRequest) request);
                HttpEntity entity = ((HttpEntityEnclosingRequest) request)
                    .getEntity();
                if (entity != null)
                {
                    // Do something useful with the entity and, when done, ensure all
                    // content has been consumed, so that the underlying connection
                    // could be re-used
                    // EntityUtils.consume(entity);
                    String r = EntityUtils.toString(enclosingRequest.getEntity());
                    if (DEBUG)
                        AppLog.logString("Entity: " + r);

                }
            }
            else
            {
                AppLog.logString("connection is closed ");
            }

        }

        // conn.receiveRequestEntity(enclosingRequest);
        // if (DEBUG) AppLog.logString( "Before input");
        // String r = EntityUtils.toString(enclosingRequest.getEntity());
        // if (DEBUG) AppLog.logString( "Entity: " + r);
        //
        // conn.sendResponseHeader(response);
        // conn.sendResponseEntity(response);
    }

    protected void displayMessage(final String message)
    {
        SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(context);
        String text = context.getString(R.string.message_ticker_text);
        Notification notification = new Notification(R.drawable.messageicon, text, System.currentTimeMillis());
        Intent startIntent = new Intent(context, AWSMessageActivity.class);
        boolean isVibrate = pref.getBoolean(Constants.PREF_VIBRATE, true);
        boolean isPlaysound = pref.getBoolean(Constants.PREF_PLAYSOUND, true);
        String notificationSound = pref.getString(Constants.PREF_RINGTONE, "");

        startIntent.putExtra(Constants.AWS_MESSAGE, message);

        PendingIntent intent = PendingIntent.getActivity(context, 0, startIntent, Intent.FLAG_ACTIVITY_NEW_TASK);

        notification.defaults = Notification.DEFAULT_LIGHTS;
        notification.flags |= (Notification.FLAG_ONLY_ALERT_ONCE | Notification.FLAG_AUTO_CANCEL);

        if (isVibrate)
            notification.vibrate = VIBRATE;

        if (isPlaysound && notificationSound.length() > 0)
            notification.sound = Uri.parse(notificationSound);

        notification.setLatestEventInfo(context,
            context.getString(R.string.message_title),
            message,
            intent);

        // notifyManager.notify(R.string.message_title, notification);
    }
}
